#include "BlockQueue.hpp"
#include "Task.hpp"
#include <unistd.h>
#include <ctime>


std::string opera = "+-*/%";

void *Consumer(void* args)
{

    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);

    while (true)
    {


        //消费
        //int data = bq->pop();
        Task t = bq->pop();
        //std::cout << "消费了一个数据: " << data << std::endl;
       t.run();

       std::cout << "处理任务: " << t.GetTask() << "运算结果是: " << t.GetResult() << "thread id: " << pthread_self() <<std::endl;
       
       sleep(1);


    }
}

void* Productor(void* args)
{
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);

    int len = opera.size();
    int x = 10;
    int y = 20;
    
    //int data = 0;
    while (true)
    {
        //生产
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 2;
        char op = opera[rand() % len];
        //usleep(10);
        
        Task st(data1,data2,op);

        bq->push(st);

        std::cout << "生产了一个任务" << st.GetTask() << "thread id: " << pthread_self() <<std::endl;
       
        //sleep(1);
    }

    return nullptr;
}



int main()
{
    srand((unsigned int)time(nullptr));

    pthread_t c[3],p[5];

    BlockQueue<Task>* bq = new BlockQueue<Task>();

    for (int i = 0; i < 3; i++)
    {
        pthread_create(c + i,nullptr,Consumer,bq);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_create(p + i,nullptr,Productor,bq);
    }
    
    for (int i = 0; i < 3; i++)
    {
        pthread_join(c[i],nullptr);
    }
  
    for (int i = 0; i < 5; i++)
    {
        pthread_join(p[i],nullptr);
    }

    delete bq;

    return 0;
}


